//------------------------------------------------------------------------------
// <copyright file="HeroesTavernControl.xaml.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Imaging;
using DotBeer.Business.Entities;
using DotBeer.Business.Components;
using System.Diagnostics;
using System.Windows.Input;
using System.Windows.Media;

namespace DotBeer.UI.WPFClient
{
    /// <summary>
    /// Interaction logic for HeroesTavernControl.xaml
    /// </summary>
    public partial class HeroesTavernControl : UserControl
    {
        #region constructors

        public HeroesTavernControl()
        {
            InitializeComponent();
        }

        #endregion

        #region properties

        public static readonly DependencyProperty SelectedSideProperty =
            DependencyProperty.Register("SelectedSide",
                                        typeof(Side),
                                        typeof(HeroesTavernControl),
                                        new PropertyMetadata(SelectedSide_Changed));

        public Side SelectedSide
        {
            get { return (Side)this.GetValue(SelectedSideProperty); }
            set { this.SetValue(SelectedSideProperty, value); }
        }

        public static readonly RoutedEvent SelectedHeroChangedEvent =
            EventManager.RegisterRoutedEvent("SelectedHeroChanged",
                                             RoutingStrategy.Direct,
                                             typeof(RoutedEventHandler),
                                             typeof(HeroesTavernControl));

        public event RoutedEventHandler SelectedHeroChanged
        {
            add { AddHandler(SelectedHeroChangedEvent, value); }
            remove { RemoveHandler(SelectedHeroChangedEvent, value); }
        }

        #endregion

        #region private methods

        private static void SelectedSide_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            HeroesTavernControl heroesTavernControl = d as HeroesTavernControl;
            heroesTavernControl.FillUniformGrids();
            heroesTavernControl.SetLogo();
        }

        private void FillUniformGrids()
        {
            this.textBlockSide.Text = this.SelectedSide.ToString();

            string[] taverns = TavernsCollectionComponent.Load().GetTavernsBySide(this.SelectedSide).Select(t => t.Name).ToArray();
            IEnumerable<HeroTavern> heroes = HeroesCollectionComponent.Load().GetHeroesBySide(this.SelectedSide);

            for (int index = 0; index < taverns.Length; index++)
            {
                UniformGrid uniformGrid = (UniformGrid)this.FindName(String.Format("uniformGrid{0}", index));
                uniformGrid.Children.Clear();

                TextBlock textBlock = (TextBlock)this.FindName(String.Format("textBlock{0}", index));
                textBlock.Text = taverns[index];

                var tavernHeroes = heroes.Where(hero => hero.TavernHero.Name == taverns[index]).OrderBy(h => h.Position);

                foreach (HeroTavern hero in tavernHeroes)
                {
                    Button button = CreateButton(hero);
                    button.ToolTip = hero.Name;

                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetValue(RenderOptions.BitmapScalingModeProperty, BitmapScalingMode.NearestNeighbor);
                    bitmapImage.BeginInit();

                    if (File.Exists(hero.ImagePath))
                        bitmapImage.UriSource = new Uri(hero.ImagePath);
                    else
                        bitmapImage.UriSource = new Uri(ApplicationPaths.QuestionMark);

                    bitmapImage.EndInit();
                    button.Content = new Image() { Source = bitmapImage };
                    uniformGrid.Children.Add(button);
                }
            }
        }

        private Button CreateButton(HeroTavern hero)
        {
            Button button = new Button();
            //button.Style = (Style)FindResource("ButtonHeroStyle");
            button.Style = (Style)FindResource("ButtonItemStyle"); ;
            button.Width = 60;
            button.Height = 60;
            button.Tag = hero;
            button.Click += (object sender, RoutedEventArgs e) =>
                {
                    ICommand command = this.GetValue(CommandProperties.CommandProperty) as ICommand;

                    if (command != null)
                        command.Execute(hero.Name);

                    this.OnSelectedHeroChanged();
                };

            return button;
        }

        private void OnSelectedHeroChanged()
        {
            RoutedEventArgs e = new RoutedEventArgs(SelectedHeroChangedEvent, this);
            base.RaiseEvent(e);
        }

        private void SetBackground()
        {
            string backgroundPath = String.Format(@"{0}Images\Taverns Background\{1}.png", AppDomain.CurrentDomain.BaseDirectory, this.SelectedSide.ToString());

            if (File.Exists(backgroundPath))
            {
                Image img = (Image)this.FindName("ImageBackground");
                img.Source = new BitmapImage(new Uri(backgroundPath));
            }
        }

        private void SetLogo()
        {
            this.ImageLogo.Source = new BitmapImage(new Uri(String.Format("{0}{1}.png", ApplicationPaths.Logo, SelectedSide.ToString())));
        }

        #endregion
    }
}
